package tempo.timing;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class Race
{
	private static Race _current;
	private static boolean save = true;

	public static Race getCurrent()
	{
		if (_current == null)
		{
			_current = new Race();
			save = false;
			_current.AddRider("Ole ", "1");
			_current.AddRider("Morten M", "2");
			_current.AddRider("Frode ", "3");
			_current.AddRider("Ingve ", "4");
			_current.AddRider("Andreas", "5");
			_current.AddRider("Arild", "6");
			_current.AddRider("Jan H", "7");
			_current.AddRider("Kristian", "8");
			_current.AddRider("Eimund", "9");
			save = true;

		}
		return _current;
	}

	private Race()
	{

	}

	ArrayList<Rider> _riders = new ArrayList<Rider>();
	ArrayList<Long> _finishTimes = new ArrayList<Long>();
	private MainWindow mainWindow;
	String FILENAME = "data.jso";

	public void AddRider(String name, String number)
	{
		_riders.add(new Rider(name, number));
		if (save)
			SaveJson();
	}

	public void AddFinishTime(long time)
	{
		_finishTimes.add(0, time);
	}

	public String[] GetRiderNames()
	{
		String[] names = new String[_riders.size()];
		for (int i = 0; i < names.length; i++)
		{
			names[i] = _riders.get(i).getRiderName();
		}
		return names;
	}

	public ArrayList<Long> GetFinishTimes()
	{
		return _finishTimes;
	}

	public ArrayList<Rider> GetRiders()
	{
		return _riders;
	}

	public void Load(JSONArray array)
	{
		_riders.clear();
		for (int i = 0; i < array.length(); i++)
		{
			Rider r = new Rider();
			try
			{
				r.LoadFrom(array.getJSONObject(i));
			} catch (JSONException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			_riders.add(r);
		}
	}

	public JSONArray Save()
	{
		JSONArray array = new JSONArray();
		for (int i = 0; i < _riders.size(); i++)
		{
			array.put(_riders.get(i).Save());
		}
		return array;

	}

	public void setContext(MainWindow mainWindow)
	{
		this.mainWindow = mainWindow;
	}

	public void SaveJson()
	{
		try
		{
			File root = Environment.getExternalStorageDirectory();
			if (root.canWrite())
			{
				File cache = new File(root + "/Android/data/tempo.timing/cache/");
				cache.mkdirs();
				File jsonDataFile = new File(root + "/Android/data/tempo.timing/cache/", FILENAME);
				FileWriter gpxwriter = new FileWriter(jsonDataFile);
				BufferedWriter out = new BufferedWriter(gpxwriter);
				out.write(Save().toString());
				out.close();
			}
		} catch (IOException e)
		{
			Log.e("Race", "Could not write file " + e.getMessage());
		}
	}

	public void LoadJson()
	{
		StringBuilder sb = new StringBuilder();
		try
		{
			File root = Environment.getExternalStorageDirectory();
			if (root.canRead())
			{
				File gpxfile = new File(root + "/Android/data/tempo.timing/cache/", FILENAME);
				FileReader gpxwriter = new FileReader(gpxfile);
				BufferedReader reader = new BufferedReader(gpxwriter);
				String line = null;

				while ((line = reader.readLine()) != null)
				{
					sb.append(line + "\n");
				}

			}
		} catch (IOException e)
		{
			Log.e("Race", "Could not write file " + e.getMessage());
		}

		try
		{
			if (sb.length() > 0)
				Load(new JSONArray(sb.toString()));
		} catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void Clear()
	{
		_riders.clear();
		_finishTimes.clear();

	}

	public boolean delete(String startNumber)
	{
		boolean val = false;
		for (int i = 0; i < _riders.size(); i++)
		{
			if (_riders.get(i).getStartNumber().equalsIgnoreCase(startNumber))
			{
				_riders.remove(i);
				val = true;
				break;
			}
		}
		if (val)
			SaveJson();
		return val;
	}

	public void resetAll()
	{
		for (int i = 0; i < _riders.size(); i++)
		{
			_riders.get(i).reset();
		}

	}
}
